import axios from "axios";
import store from "@/store";

import { getSecret } from "./index.js";

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    const headers = config.headers || {};
    config.headers = {
      ...headers,
      ...getSecret(),
    };
    if(store.getters.token){
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const { success, message, data } = response.data;
    if (success) {
      return data;
    } else {
      return Promise.reject(message);
    }
  },
  (error) => {
    if(error.response && error.response.status === 401){
      store.dispatch('user/logout')
    }
    return Promise.reject(error);
  }
);

export default service;
